package com.w.picture.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.w.picture.annotation.RoleCheck;
import com.w.picture.api.aliyunai.AliYunAiApi;
import com.w.picture.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.w.picture.api.aliyunai.model.ImageOutPaintingResponse;
import com.w.picture.api.imagesrarch.ImageSearchApiFacade;
import com.w.picture.api.imagesrarch.model.ImageSearchResult;
import com.w.picture.common.BaseResponse;
import com.w.picture.common.DeleteRequest;
import com.w.picture.common.ResultUtils;
import com.w.picture.constans.UserConstant;
import com.w.picture.exception.BusinessException;
import com.w.picture.exception.ErrorCode;
import com.w.picture.exception.ThrowUtils;
import com.w.picture.manager.auth.SpaceUserAuthManager;
import com.w.picture.manager.auth.StpKit;
import com.w.picture.manager.auth.annotation.SaSpaceCheckPermission;
import com.w.picture.manager.auth.model.SpaceUserPermissionConstant;
import com.w.picture.mode.dto.picture.*;
import com.w.picture.mode.entity.Picture;
import com.w.picture.mode.entity.Space;
import com.w.picture.mode.entity.User;
import com.w.picture.mode.enums.PictureReviewStatusEnum;
import com.w.picture.mode.vo.PictureTagCategoryVo;
import com.w.picture.mode.vo.PictureVO;
import com.w.picture.service.PictureService;
import com.w.picture.service.SpaceService;
import com.w.picture.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Title: PictureController
 * @Author wzp
 * @Date 2024/12/31 15:34
 * @description: 图片处理
 */
@RestController
@RequestMapping("/picture")
public class PictureController {

    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private SpaceService spaceService;
    @Resource
    private AliYunAiApi aliYunAiApi;
    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    private final Cache<String, Object> LOCAL_CACHE = Caffeine.newBuilder()
            .maximumSize(10000L) // 设置最大缓存数量
            .expireAfterWrite(Duration.ofMinutes(5)) // 设置缓存过期时间 5分钟
            .build();


    /**
     * 上传图片
     *
     * @param multipartFile
     * @param pictureUploadRequest
     * @param request
     * @return
     */
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    @RoleCheck(UserConstant.DEFAULT_ROLE)
    @PostMapping("/upload")
    public BaseResponse<PictureVO> uploadPicture(@RequestPart("file") MultipartFile multipartFile,
                                                 PictureUploadRequest pictureUploadRequest,
                                                 HttpServletRequest request) {

        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, "file", pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 批量删除图片
     */
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    @RoleCheck(UserConstant.DEFAULT_ROLE)
    @PostMapping("/deleteBatch")
    public BaseResponse<Boolean> deleteBatchPicture(@RequestBody List<Long> ids, HttpServletRequest request) {
        // 检查参数是否为空或无效
        ThrowUtils.throwIf(ids == null || ids.isEmpty(), ErrorCode.PARAMS_ERROR, "列表不能为空");

        // 获取当前登录用户信息
        User loginUser = userService.getLoginUser(request);

        // 遍历ID列表，进行删除操作
        for (Long id : ids) {
            // 校验参数有效性
            ThrowUtils.throwIf(id == null || id <= 0, ErrorCode.PARAMS_ERROR, "无效的ID");

            // 根据ID获取图片信息
            Picture picture = pictureService.getById(id);
            ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR, "找不到对应的图片");

            // 权限检查：仅管理员和图片上传者可以删除
            if (!loginUser.getId().equals(picture.getUserId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR.getCode(), "没有足够的权限删除此图片");
            }

            // 尝试删除图片
            boolean deleted = pictureService.removeById(id);
            ThrowUtils.throwIf(!deleted, ErrorCode.OPERATION_ERROR, "删除图片失败");
            pictureService.clearPictureFile(picture);
        }

        // 如果所有图片都成功删除，则返回成功响应
        return ResultUtils.success("批量删除成功");
    }

    /**
     * 删除图片
     */
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    @RoleCheck(UserConstant.DEFAULT_ROLE)
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        pictureService.deletePicture(deleteRequest.getId(), userService.getLoginUser(request));
        return ResultUtils.success(true);
    }

    /**
     * 更新图片（仅管理员可用）
     */
    @PostMapping("/update")
    @RoleCheck(value = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest, HttpServletRequest request) {
        if (pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest, picture);
        // 注意将 list 转为 string
//        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        // 数据校验
        pictureService.validPicture(picture);
        // 判断是否存在
        long id = pictureUpdateRequest.getId();
        Picture oldPicture = pictureService.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);

        // 填充审核参数
        User loginUser = userService.getLoginUser(request);
        pictureService.fillReviewParams(picture, loginUser);

        // 操作数据库
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取图片（仅管理员可用）
     */
    @GetMapping("/get")
    @RoleCheck(value = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPictureById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(picture);
    }

    /**
     * 根据 id 获取图片（封装类）
     * 用户正常情况下是不会得到未通过审核的图片ID的所以这里暂时不需要进行图片审核状态的校验
     */
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 空间权限校验
        Long spaceId = picture.getSpaceId();
        Space space = null; // 空间的图片，需要校验权限
        if (spaceId != null) {
            // 修改为Sa-Token校验,编程式校验
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR, "没有权限查看此图片");
            space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            // 已经修改为,使用Sa-Token注解鉴权
//            User loginUser = userService.getLoginUser(request);
//            pictureService.checkPictureAuth(loginUser, picture);
        }

        // 获取权限列表
        User loginUser = userService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        PictureVO pictureVO = pictureService.getPictureVO(picture, request);
        pictureVO.setPermissionList(permissionList);
        // 获取封装类
        return ResultUtils.success(pictureVO);
    }

    /**
     * 分页获取图片列表（仅管理员可用）
     */
    @PostMapping("/list/page")
    @RoleCheck(value = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        long current = pictureQueryRequest.getPageNum();
        long size = pictureQueryRequest.getPageSize();
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取图片列表（封装类）
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                             HttpServletRequest request) {
        long current = pictureQueryRequest.getPageNum();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 空间权限校验
        Long spaceId = pictureQueryRequest.getSpaceId();
        // 公开图库
        if (spaceId == null) {
            // 普通用户默认只能查看已过审的公开数据
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            pictureQueryRequest.setNullSpaceId(true);
        } else {

            // 修改为Sa-Token校验,编程式校验
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR, "没有权限查看此图片");

//            // 私有空间
//            User loginUser = userService.getLoginUser(request);
//            Space space = spaceService.getById(spaceId);
//            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
//            if (!loginUser.getId().equals(space.getUserId())) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR.getCode(), "没有空间权限");
//            }
        }


        // 增加普通用户查询的权限限制,,这个接口本来就是给普通用户查看的,因此只需要在这里限制查看的内容为通过审核的
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());

        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        // 获取封装类
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage, request));
    }

    /**
     * 使用多级缓存(本地缓存caffeine 分布式缓存redis)版本
     * 流程:
     * 1.先从本地缓存(caffeine 咖啡因)获取数据,如果有直接返回,如果没有再从redis中获取数据,并添加到本地缓存中
     * 2.如果redis中不存在数据,则从数据库中获取数据,并添加到本地缓存和redis中
     *
     * @param pictureQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo/cache")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                                      HttpServletRequest request) {
        long current = pictureQueryRequest.getPageNum();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);

        // 增加普通用户查询的权限限制,,这个接口本来就是给普通用户查看的,因此只需要在这里限制查看的内容为通过审核的
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());

        // 查询缓存
        String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
        String hashKey = DigestUtils.sha256Hex(queryCondition);
        String redisKey = "wpicture:listPictureVOByPage:" + hashKey;

        // 先本地缓存
        Page<PictureVO> result = (Page<PictureVO>) LOCAL_CACHE.getIfPresent(redisKey);
        if (result != null) {
            return ResultUtils.success(result);
        }
        // 本地缓存没有,访问redis
        result = (Page<PictureVO>) redisTemplate.opsForValue().get(redisKey);
        if (result != null) {
            LOCAL_CACHE.put(redisKey, result); // 缓存到本地缓存中
            return ResultUtils.success(result);
        }
        // redis也没有,查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);
        // 得到的结果,缓存到本地缓存和redis中
        LOCAL_CACHE.put(redisKey, pictureVOPage);
        int cacheExpireTime = 300 + RandomUtil.randomInt(0, 300); // 5-10分钟随机过期,防止雪崩
        redisTemplate.opsForValue().set(redisKey, pictureVOPage, cacheExpireTime, TimeUnit.SECONDS);

        // 获取封装类
        return ResultUtils.success(pictureVOPage);
    }

    /**
     * 编辑图片（给用户使用）
     */
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    @PostMapping("/edit")
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        pictureService.editPicture(pictureEditRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 获取标签和分类
     * 由于项目前期规模不大，暂且使用硬编码。暂时不考虑使用数据库表
     *
     * @return 图片标签和分类
     */
    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategoryVo> listPictureTagCategory() {
        PictureTagCategoryVo pictureTagCategory = new PictureTagCategoryVo();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }

    /**
     * 审核图片
     *
     * @param pictureReviewRequest 审核请求
     * @param request              servlet请求
     * @return
     */
    @RoleCheck(UserConstant.ADMIN_ROLE)
    @PostMapping("/review")
    public BaseResponse<Boolean> doPictureReview(@RequestBody PictureReviewRequest pictureReviewRequest,
                                                 HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        pictureService.doPictureReview(pictureReviewRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 通过 URL 上传图片（可重新上传）
     */
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    @PostMapping("/upload/url")
    @RoleCheck(UserConstant.DEFAULT_ROLE)
    public BaseResponse<PictureVO> uploadPictureByUrl(
            @RequestBody PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String fileUrl = pictureUploadRequest.getFileUrl();
        PictureVO pictureVO = pictureService.uploadPicture(fileUrl, "url", pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }


    /**
     * 批量抓取图片并上传
     *
     * @param pictureUploadByBatchRequest 图片上传请求
     * @param request                     HttpServletRequest
     * @return 上传成功数量
     */
    @PostMapping("/upload/batch")
    @RoleCheck(UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> uploadPictureByBatch(@RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest,
                                                      HttpServletRequest request) throws UnsupportedEncodingException {

        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser));
    }

    /**
     * 以图搜图
     * 注意:该接口目前不支持webp格式图片(百度识图的接口不支持), 因为图片压缩时,会先转成webp格式,再压缩成jpg格式,但是webp格式不支持缩放
     * 解决方式:
     * 1.保存原图,使用原图去搜索,,目前使用的是这种方式
     * 2.使用缩略图,也可以使用这种方式,因为数据库都存了
     * 3.转换格式
     */
    @PostMapping("/search/picture")
    public BaseResponse<List<ImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR);
        Picture oldPicture = pictureService.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        String url = oldPicture.getHost() + oldPicture.getOriginalUrl();
        List<ImageSearchResult> resultList = ImageSearchApiFacade.searchImage(url);
        return ResultUtils.success(resultList);
    }

    /**
     * 根据颜色搜索图片
     *
     * @param searchPictureByPictureRequest 请求
     * @param request
     * @return
     */
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    @PostMapping("/search/color")
    public BaseResponse<List<PictureVO>> searchPictureByColor(@RequestBody SearchPictureByColorRequest searchPictureByPictureRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
        String picColor = searchPictureByPictureRequest.getPicColor();
        Long spaceId = searchPictureByPictureRequest.getSpaceId();
        User loginUser = userService.getLoginUser(request);
        List<PictureVO> resultList = pictureService.searchPictureByColor(spaceId, picColor, loginUser);
        return ResultUtils.success(resultList);
    }

    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    @PostMapping("/edit/batch")
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.editPictureByBatch(pictureEditByBatchRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 创建 AI 扩图任务
     */
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    @PostMapping("/out_painting/create_task")
    public BaseResponse<ImageOutPaintingResponse> createPictureOutPaintingTask(
            @RequestBody CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest,
            HttpServletRequest request) {
        if (createPictureOutPaintingTaskRequest == null || createPictureOutPaintingTaskRequest.getPictureId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        ImageOutPaintingResponse response = pictureService.createPictureOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser);
        return ResultUtils.success(response);
    }

    /**
     * 查询 AI 扩图任务
     */
    @GetMapping("/out_painting/get_task")
    public BaseResponse<GetOutPaintingTaskResponse> getPictureOutPaintingTask(String taskId) {
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetOutPaintingTaskResponse task = aliYunAiApi.getTaskResult(taskId);
        return ResultUtils.success(task);
    }

}
